import React, { useState, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { Button, Drawer, Modal, Popconfirm, Form, Input, message } from 'antd';
import { EditableProTable } from '@ant-design/pro-table';
import { getDictionaryList, getDictionaryDetails, updateDictionaryDetails, createDictionaryDetails, createDictionaryDetailsA, deleteDictionaryDetails, updateDataDictionaryB } from '@/services/ant-design-pro/system'; // 假设你有一个 API 模块

const DictionaryManagement = () => {
  const actionRef = useRef();
  const editableFormRef = useRef();
  const [visible, setVisible] = useState(false);
  const [details, setDetails] = useState([]);
  const [dictionaryCode, setDictionaryCode] = useState('');
  const [editableKeys, setEditableKeys] = useState([]);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [form] = Form.useForm();
  useEffect(() => {
    console.log('details updated:', details);
  }, [details]);

  const columns = [
    {
      title: '字典名称',
      dataIndex: 'dictionaryName',
      key: 'dictionaryName',
      search: false
    },
    {
      title: '字典编码',
      dataIndex: 'dictionaryCode',
      key: 'dictionaryCode',
      search: false
    },
    {
      title: '字典排序',
      dataIndex: 'dictionarySort',
      key: 'dictionarySort',
      search: false,
      hidden: true,
      render: (text) => text || '-',
    },
    {
      title: '操作',
      key: 'action',
      search: false,
      render: (_, record) => (
        <Button type="link" onClick={() => handleViewDetails(record.id)}>
          查看详情
        </Button>
      ),
    },
  ];

  const handleViewDetails = async (code) => {
    setDictionaryCode(code);
    const details = await getDictionaryDetails(code);
    setDetails(details);
    setEditableKeys([]); // 初始化 editableKeys 为空数组
    setVisible(true);
  };

  const handleUpdateDetails = async (updatedDetails) => {
    console.log('updatedDetails', updatedDetails);
    await updateDictionaryDetails(dictionaryCode, updatedDetails);
    actionRef.current.reload();
    setVisible(false);
  };

  const handleDelete = async (code) => {
    console.log(editableFormRef,'-=editableFormRef')
    await deleteDictionaryDetails(code);
    const updatedDetails = details.filter(item => item.id !== code);
    setDetails(updatedDetails);
  };

  const handleSave = async (rowKey, data, row) => {
    console.log('rowKey', rowKey.toString().includes('abc'));
    if (rowKey.toString().includes('abc')) {
      await createDictionaryDetails({ parentId: dictionaryCode, ...data, 'id': '' });
    } else {
      await updateDataDictionaryB(data);
    }
    // 重新获取字典详情数据
    const updatedDetails = await getDictionaryDetails(dictionaryCode);
    setTimeout(() => {
      setDetails(updatedDetails)
    }, 1000);
  };

  const handleAddDictionary = async () => {
    try {
      const values = await form.validateFields();
      await createDictionaryDetailsA(values);
      message.success('添加成功');
      setAddModalVisible(false);
      actionRef.current.reload();
      // 重新获取字典详情数据
      const updatedDetails = await getDictionaryDetails(dictionaryCode);
      setDetails(updatedDetails);
      setTimeout(() => {
        setDetails(updatedDetails)
      }, 1000);
      console.log(details,'---')
    } catch (error) {
      message.error('添加失败');
    }
  };

  return (
    <>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        request={getDictionaryList}
        rowKey="id"
        search={false}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle="字典管理"
        toolBarRender={() => [
          <Button key="add" type="primary" onClick={() => { setAddModalVisible(true); form.resetFields() }}>
            添加字典
          </Button>,
        ]}
      />

      <Drawer
        title="字典详情"
        open={visible}
        onClose={() => setVisible(false)}
        width={900}
      >
        <EditableProTable
          rowKey="id"
          editableFormRef={editableFormRef}
          controlled={true}
          columns={[
            { title: '字典项', dataIndex: 'dictionaryName', key: 'dictionaryName', valueType: 'text' },
            { title: '值', dataIndex: 'dictionaryCode', key: 'dictionaryCode', valueType: 'text' },
            { title: '排序', dataIndex: 'dictionarySort', key: 'dictionarySort', valueType: 'text' },
            {
              title: '操作',
              key: 'action',
              valueType: 'option',
              render: (text, record, _, action) => [
                <a
                  key="editable"
                  onClick={() => {
                    action?.startEditable?.(record.id);
                  }}
                >
                  编辑
                </a>,
                <Popconfirm
                  key="delete"
                  title="确定删除该数据吗？"
                  onConfirm={() => handleDelete(record.id)}
                >
                  <a key="delete">删除</a>
                </Popconfirm>,
              ],
            },
          ]}
          value={details}
          onChange={(updatedDetails) => {
            setDetails(updatedDetails);
          }}
          recordCreatorProps={{
            newRecordType: 'dataSource',
            record: () => ({ id: 'abc' + (Math.random() * 1000000).toFixed(0) }),
          }}
          editable={{
            type: 'multiple',
            editableKeys,
            onSave: async (rowKey, data, row) => {
              await handleSave(rowKey, data, row); // 在保存时调用保存接口
            },
            onChange: setEditableKeys,
          }}
        />
      </Drawer>

      <Modal
        title="添加字典"
        open={addModalVisible}
        onOk={handleAddDictionary}
        onCancel={() => setAddModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="dictionaryCode"
            label="字典编码"
            rules={[{ required: true, message: '请输入字典编码' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="dictionaryName"
            label="字典名称"
            rules={[{ required: true, message: '请输入字典名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="dictionarySort"
            label="字典排序"
            rules={[{ required: true, message: '请输入字典排序' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default DictionaryManagement;